package com.andova.pipeline.impl

import android.os.Handler
import com.andova.ext.e
import com.andova.pipeline.Pipeline

class GLEventPipeline private constructor() : Pipeline {
    private object Holder {
        val INSTANCE: Pipeline = GLEventPipeline()
    }

    companion object {
        private val INSTANCE: Pipeline by lazy { Holder.INSTANCE }
        fun isMe(pipeline: Pipeline): Boolean = run { INSTANCE == pipeline }
    }

    private var eventPipeline: EventPipeline? = null
    private fun check() {
        eventPipeline = eventPipeline ?: EventPipeline.create("GLEventPipeline")
    }

    override fun queueEvent(event: Runnable, front: Boolean) {
        check()
        eventPipeline?.queueEvent(event)
    }

    override fun queueEvent(event: Runnable, delayed: Long) {
        check()
        eventPipeline?.queueEvent(event, delayed)
    }

    override fun quit() {
        eventPipeline?.run {
            eventPipeline?.quit()
            eventPipeline = null
            e("GLEventPipeline quited")
        }
    }

    override fun started(): Boolean {
        eventPipeline ?: return false
        e("GLEventPipeline started")
        return eventPipeline?.started() ?: false
    }

    override fun getName(): String = eventPipeline?.getName() ?: "UNKNOWN"
    override fun getHandler(): Handler = eventPipeline!!.getHandler()
    override fun sleep(): Unit = run { eventPipeline?.sleep() }
    override fun wake(): Unit = run { eventPipeline?.wake() }
}